package tableprocessor;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableProperties;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class MicrosoftOfficeFilesProcessor implements FileInterface
{
    private enum Type{DOC,DOCX,XLS,XLSX};
    private StringBuffer buf = new StringBuffer();
    public boolean isIam(String path)
    {
        if (getFormat(path)!=null)
        {
            return true;
        }
        return false;
    }
    public Iterator<Table> parse(String path)
    {
        return formatParse(path,getFormat(path));
    }
    public Table getTable(String path)
    {
        return null;
    }
    private Type getFormat(String path)
    {
            try
            {
                XWPFDocument xdoc = new XWPFDocument(new FileInputStream(path));
                return Type.DOCX;
            }
            catch (Exception e){/*e.printStackTrace();*/}
            try
            {
                HWPFDocument doc = new HWPFDocument(new FileInputStream(path));
                return Type.DOC;
            }catch(Exception e){/*e.printStackTrace();*/}
            try
            {
                XSSFWorkbook xdoc = new XSSFWorkbook(new FileInputStream(path));
                return Type.XLSX;
            }
            catch (Exception e){/*e.printStackTrace();*/}
            try
            {
                HSSFWorkbook doc = new HSSFWorkbook(new FileInputStream(path));
                return Type.XLS;
            }catch(Exception e){/*e.printStackTrace();*/}
       return null;
    }
    private Iterator<Table> formatParse(String path,Type t)
    {
        switch(t)
        {
            case DOC:
            {
                return parseDoc(path);
            }
            case DOCX:
            {
                return parseDocX(path);
            }
            case XLS:
            {
                return parseXLS(path);
            }
        }
        return null;
    }
    private Iterator<Table> parseXLS(String path)
    {
        List<Table> tlist = new ArrayList<Table>();
        Table t = new Table();
        tlist.add(t);
        File inputWorkbook = new File(path);
        Workbook w;
        try
        {
            w = Workbook.getWorkbook(inputWorkbook);
            int shitNum = w.getNumberOfSheets();
            for (int i = 0 ; i < shitNum; i++)
            {
                Sheet sheet = w.getSheet(i);
                for (int j = 0 ; j < sheet.getRows(); j++)
                {
                   Cell [] cellMas = sheet.getRow(j);
                   t.insertRow(j);
                   for (int k = 0 ; k < cellMas.length; k++)
                   {
                       if (!cellMas[k].getContents().isEmpty())
                       {
                           t.addToRow(j, cellMas[k].getContents());
                       }
                   }
                }
            }
        }
        catch (IOException ex)
        {
           ex.printStackTrace();
        }
        catch (BiffException ex)
        {
            ex.printStackTrace();
        }
        return tlist.iterator();
    }
    private Iterator<Table> parseDoc(String path)
    {
        //parse1(path);
        return parse1(path);
    }
     private Iterator<Table> parseDocX(String path)
     {
          List<Table> tlist = new ArrayList<Table>();

          return tlist.iterator();
     }
    private void printToBuffer(DefaultMutableTreeNode node,PriceDAO pdao,StringBuffer buf)
    {
//        Iterator <String> siter = pdao.getRowByCathegory(node, 0);
//        while (siter.hasNext())
//        {
//            System.out.println(siter.next());
//        }
         buf.append("<br>"+node.toString());
        if (node.getAllowsChildren())
        {
            if (pdao.isHasColumns(node))
            {
                buf.append("<table border=1 width=100%>");
                Iterator<ColumnPare> citer = pdao.getColumnsForCathegory(node);
                buf.append("<tr>");
                while (citer.hasNext())
                {
                    buf.append("<td bgcolor=#a19696>");
                    buf.append(citer.next().getDbcol().getName());
                    buf.append("</td>");
                }
                buf.append("</tr>");
                int nrows = pdao.getRowsInCathegory(node);
                if (nrows >0)
                {
                    for (int i = 1 ; i <=nrows; i++)
                    {
                        buf.append("<tr>");
                        Iterator<String> siter = pdao.getRowByCathegory(node, i);
                        while (siter.hasNext())
                        {
                            buf.append("<td>"+siter.next()+"</td>");
                        }
                        buf.append("</tr>");
                    }
                }
               buf.append("</table>");
            }
            else
            {
                for (int i = 0; i < node.getChildCount(); i++)
                {
                    printToBuffer((DefaultMutableTreeNode) node.getChildAt(i),pdao,buf);
                }
            }
        }
    }
    public void saveToDoc(String path)
    {
       PriceDAO pdao= new PriceDAO();
       CathegoryStaticTreeFactory.setPriceDAO(pdao);
       pdao.fillTree();
       DefaultMutableTreeNode root = (DefaultMutableTreeNode) pdao.getTree().getModel().getRoot();
       StringBuffer htmlBuffer = new StringBuffer();
       htmlBuffer.append("<html><body>");
       if (root.getAllowsChildren())
       {
            for (int i = 0 ; i < root.getChildCount(); i++)
            {
               printToBuffer((DefaultMutableTreeNode) root.getChildAt(i),pdao,htmlBuffer);
            }
       }
       htmlBuffer.append("</body></html>");
       PrintWriter writer = null;
       try
       {
           writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path)));
           writer.write(htmlBuffer.toString());
           writer.close();
           JOptionPane.showMessageDialog(null, "Прайс сохранен по пути :"+path);
       }
       catch (Exception ex)
       {
           htmlBuffer.delete(0, htmlBuffer.length());
           JOptionPane.showMessageDialog(null, "Не могу сохранить файл...");
       }
    }
    public void addCategory(String content) 
    {
        buf.append(content);
    }
    //test methods
    private Iterator<Table> parse1(String path)
    {
       FileInputStream finStream = null;
       List<Table> tlist = new ArrayList<Table>();
       Table t = new Table();
        try {

              tlist.add(t);
            File docFile = new File(path);
            finStream = new FileInputStream(docFile.getAbsolutePath());
            HWPFDocument doc = new HWPFDocument(finStream);
            WordExtractor wordExtract = new WordExtractor(doc);
            String[] dataArray = wordExtract.getParagraphText();
            for (int i = 0; i < dataArray.length; i++)
            {
                if (!dataArray[i].isEmpty())
                {
                    t.insertRow(i);
                    //for (int j = 0 ; j < dataArray.length; j++)
                    //{
                        t.insertData(i, 0, dataArray[i].substring(0, dataArray[i].length()-1));
                       // System.out.println(dataArray[i].substring(0, dataArray[i].length()-1));
                    //}
                    
                }
                //System.out.println(dataArray[i]);
            }
          
            return tlist.iterator();
        }
        catch (IOException ex)
        {
           ex.printStackTrace();
            return null;
        }

        finally
        {
            try {
                finStream.close();
                return tlist.iterator();
            } catch (IOException ex) {
                ex.printStackTrace();
                 return null;
            }
        }
    }
    private Iterator<Table> parse2(String path)
    {
        FileInputStream finStream = null;
        List<Table> tlist = new ArrayList<Table>();
        Table t = new Table();
        tlist.add(t);
        try
        {
           HWPFDocument doc = new HWPFDocument(new FileInputStream(path));
           Range range = doc.getRange();
           TableIterator iter = new TableIterator(range);
           org.apache.poi.hwpf.usermodel.Table table = null;
           while(iter.hasNext())
           {
              table = iter.next();
              for (int i = 0; i < table.numRows(); i++)
              {
                  t.insertRow(i);
                 for (int j = 0; j < table.getRow(i).numCells(); j++)
                 {
                       TableCell tc = table.getRow(i).getCell(j);
                       t.setData(i, j, tc.text());
                 }
               }
            }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        return tlist.iterator();
    }
}

